package com.example.demo.sentinel;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
@RequestMapping("/sentinel")
public class SentinelController {
    private Integer count = 0;

    @SneakyThrows
    @GetMapping("/flow/control")
    @SentinelResource(value = "flowControl", blockHandler = "handleBlock", fallback = "exceptHandler")
    public String flowControl() {
        Thread.sleep(10);
        return "hello flow control!" + count++;
    }

    // 发生异常时 进入该方法
    public String exceptHandler(BlockException ex) {
        log.info("发生异常{}", count);
        return "发生异常";
    }

    // sentinel发生异常时 BlockException 进入该方法
    public String handleBlock(BlockException ex) {
        log.info("发生限流、降级和熔断{}", count);
        return "发生降级、降级和熔断" + ex;
    }
}
